package top.chmin.project.cloud.builder;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import top.chmin.project.cloud.common.entity.auto.EntityDao;
import top.chmin.project.cloud.common.entity.column.auto.EntityColumn;
import top.chmin.project.cloud.common.entity.column.auto.EntityColumnDao;
import top.chmin.project.cloud.common.entity.label.value.auto.EntityLabelValue;
import top.chmin.project.cloud.common.entity.label.value.auto.EntityLabelValueDao;

import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * chmin
 * 2023/12/15 15:21
 * cloud-builder
 */
@Component
public class PageColumnInitBuilder implements Builder {

    @Resource
    EntityDao entityDao;
    @Resource
    EntityColumnDao entityColumnDao;
    @Resource
    EntityLabelValueDao entityLabelValueDao;

    @Override
    public void build(BuilderConfig config) {
        String content = """
                import {BasePage, BaseColumn} from "../../%sts/type";
                import {replace, stampToDatetimeText} from "../../%sts/util";
                import {h} from "vue";
                                
                export let #e.fieldName#ColumnInit = (page: BasePage) => {
                    page.columns.push(replace(new BaseColumn('index', ''), {
                      width: 60
                    }))
                    page.columns.push(replace(new BaseColumn('id', 'ID'), {
                      sorter: 'default',
                      defaultSortOrder: 'descend',
                      width: 80
                    }))
                // field column auto
                // field label auto
                    page.columns.push(new BaseColumn('createBy', '创建人'))
                    page.columns.push(new BaseColumn('updateBy', '修改人'))
                    page.columns.push(replace(new BaseColumn('createTime', '创建时间'), {
                      render: (row: any) => {
                        return h('span', stampToDatetimeText(row.createTime))
                      }
                    }))
                    page.columns.push(replace(new BaseColumn('updateTime', '修改时间'), {
                      render: (row: any) => {
                        return h('span', stampToDatetimeText(row.updateTime))
                      }
                    }))
                }""".formatted(
                Stream.of(StrUtil.toUnderlineCase(config.getEntity().getClassName()).split("_"))
                        .map(s -> "../")
                        .collect(Collectors.joining()),
                Stream.of(StrUtil.toUnderlineCase(config.getEntity().getClassName()).split("_"))
                        .map(s -> "../")
                        .collect(Collectors.joining())
        );

        String fileName = "\\view\\%sauto\\%sColumnInit.ts".formatted(
                Stream.of(StrUtil.toUnderlineCase(config.getEntity().getClassName()).split("_"))
                        .map(s -> s + "\\")
                        .collect(Collectors.joining()),
                StringUtils.uncapitalize(config.getEntity().getClassName())
        );

        saveUi(config,
                fileName,
                content,
                true
        );

        config.getEntityColumnList().stream()
                .filter(f -> !"id".equals(f.getFieldName()))
                .filter(f -> !"createBy".equals(f.getFieldName()))
                .filter(f -> !"createTime".equals(f.getFieldName()))
                .filter(f -> !"updateBy".equals(f.getFieldName()))
                .filter(f -> !"updateTime".equals(f.getFieldName()))
                .forEach(f -> {
                    if ("LocalDateTime".equals(f.getSimpleType())) {
                        appendUi(config, f,
                                "// field column auto",
                                "page.columns.push(replace(new BaseColumn('#f.fieldName#', '#f.remark#')",
                                """
                                        page.columns.push(replace(new BaseColumn('#f.fieldName#', '#f.remark#'), {
                                          render: (row: any) => {
                                            return h('span', stampToDatetimeText(row.#f.fieldName#))
                                          }
                                        }))""",
                                fileName);
                    } else {
                        appendUi(config, f,
                                "// field column auto",
                                "page.columns.push(new BaseColumn('#f.fieldName#', '#f.remark#'))",
                                "page.columns.push(new BaseColumn('#f.fieldName#', '#f.remark#'))",
                                fileName);
                    }
                });

        config.getEntityColumnRelationList().forEach(r -> {
            EntityColumn column = config.getEntityColumnList().stream().filter(f -> f.getFieldCode().equals(r.getSourceFieldCode())).findFirst().orElseThrow();

            EntityLabelValue entityLabelValue = getEntityLabelValue(entityLabelValueDao, r.getTargetTableCode())
                    .stream().filter(e -> e.getValueFieldCode().equals(r.getTargetFieldCode())).findFirst().orElseThrow();
            EntityColumn targetLabel = getEntityColumn(entityColumnDao, entityLabelValue.getLabelFieldCode());

            appendUi(
                    config,
                    column,
                    "// field label auto",
                    """
                            page.columns.push(new BaseColumn('%sLabel',""".formatted(
                            column.getFieldName()
                    ),
                    """
                            page.columns.push(new BaseColumn('%sLabel', '%s'))""".formatted(
                            column.getFieldName(),
                            targetLabel.getRemark()
                    ),
                    fileName
            );
        });
    }
}
